<?php
// +----------------------------------------------------------------------
// | huhaiqin，2023.03.20
// | hhq110@126.com
// | ThinkPHP3.2.3 数据库备份
// +----------------------------------------------------------------------
namespace System\Org;

class Backup{

    private $save_path = ''; //保存路由，相当于配置文件，可以对外访问

    // 构造函数
    function __construct(){
        $this->save_path = C('DATABASE_BACKUP'); //创建对象时，读取配置文件的参数
    }

    /**
     * huhaiqin，2023.03.20
     * 数据库备份操作
     */
    public function backups() {
        header('Content-Type:text/html;charset=utf8');
        ini_set("max_execution_time", "0");//代码运行时间不限制  防止备份失败
        ini_set('memory_limit', '1024M');//设置内存 根据需求可以修改
        date_default_timezone_set("PRC");
        header("Content-Type:text/html;charset=utf-8");
        $host     =  C('DB_HOST');
        $user     =  C('DB_USER'); //数据库账户
        $pwd      =  C('DB_PWD'); //数据库密码
        $dbname   =  C('DB_NAME'); //数据库名称
        $con      =  mysqli_connect("$host","$user","$pwd","$dbname");
        mysqli_select_db($con,$dbname);
        $mysql    = "set charset utf8;\r\n";#for mysql>=5.0
        mysqli_query($con,"SET NAMES 'UTF8'");
        $q1       = mysqli_query($con,"show tables");
        while($t  = mysqli_fetch_array($q1)){
            $table= $t[0];
            $q2   = mysqli_query($con,"show create table `$table`");
            $sql  = mysqli_fetch_array($q2);
            $mysql.=$sql['Create Table'].";\r\n\r\n";#DDL
            $q3   = mysqli_query($con,"select * from `$table`");
            while($data = mysqli_fetch_assoc($q3))
            {
                $keys   = array_keys($data);
                $keys   = array_map('addslashes',$keys);
                $keys   = join('`,`',$keys);
                $keys   = "`".$keys."`";
                $vals   = array_values($data);
                $vals   = array_map('addslashes',$vals);
                $vals   = join("','",$vals);
                $vals   = "'".$vals."'";
                $mysql .= "insert into `$table`($keys) values($vals);\r\n";
                unset($data);
            }
            $mysql     .= "\r\n";
            unset($t);
        }
        mysqli_close($con);
        $filename      = date('Ymj_His').".sql"; //文件名为当天的日期
        $time          = time();
        $path          = $this->save_path;
        // 检查目录是否存在
        if(!is_dir($path)){
            // 新建目录
            mkdir($path, 0777, true);
        }
        $file_name     = $path.$filename;
        $fp            = fopen($file_name,'w');
        fputs($fp,$mysql);
        fclose($fp);
        $fp            = fopen($file_name,"r");
        $file_size     = filesize($file_name);

        // echo 'filesize = '.$file_size.'<br>';
        // echo 'filename = '.$filename.'<br>';
        if ($file_size){
            return ['file_size'=>$file_size,'file_name'=>$filename];
        }else{
            return false;
        }
        // exit;
    }

    /** 
     * huhaiqin，2023.03.20
     * 下载文件
     */
    public function download($file_name = '', $file_size = 0){
        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".$file_size);
        header("Content-Disposition: attachment; filename=".$this->save_path.$file_name);
        //   这里一定要使用echo 进行输出，否则下载的文件是空白的
        $fp = fopen($this->save_path.$file_name,'r'); // 打开文件
        echo fread($fp,$file_size);
        fclose($fp);
        exit;
    }

    /**
     * huhaiqin，2023.03.20
     * 删除数据库备份文件
     */
    public function del_file($file_name){
        unlink($this->save_path.$file_name); // 删除备份文件
    }
}
